<?php

namespace Business;

class User extends Base {

	public function register($email, $password, $ip) {
		if (!\Lib\Util\Comm::checkEmailFormat($email)) {
			$this->throwException('请输入正确的Email', \Entity\ErrorCode::EMAIL_FORMAT);
		}
		$user = $this->getUserInfoByEmail($email);
		if ($user) {
			$this->throwException('Email已经存在！', \Entity\ErrorCode::EMAIL_EXIST);
		}
		$len = strlen($password);
		if ($len < 6 || $len > 24) {
			$this->throwException('请输入6到24的密码！', \Entity\ErrorCode::PASSWORD_ERROR);
		}
		$password = \Util\User::encodePassword($password);
		$userId = \Data\User::instance()->addUser($email, $password, $ip);
		return $userId;
	}

    public function registerIndex($mask, $email, $username, $password, $breed, $verify, $sex, $ip) {
        $this->checkVerify($verify, $mask);
		if (!\Lib\Util\Comm::checkEmailFormat($email)) {
			$this->throwException('请输入正确的Email', \Entity\ErrorCode::EMAIL_FORMAT);
		}
        if (mb_strlen($username) > 12 || mb_strlen($username) < 1) {
            $this->throwException('请输入1到12位的狗狗名字', \Entity\ErrorCode::USER_NAME_ERROR);
        }
        if (strlen($password) > 24 || strlen($password) < 1) {
            $this->throwException('请输入6到24位的密码', \Entity\ErrorCode::PASSWORD_ERROR);
        }
        $breed = trim($breed);
        if (!$breed) {
            $this->throwException('请选择正确的品种');
        }
        $breedId = \Business\Breed::instance()->getBreedIdByName($breed);
        if (!$breedId) {
            $this->throwException('请选择正确的品种');
        }
		$user = $this->getUserInfoByEmail($email);
		if ($user) {
			$this->throwException('Email已经存在！', \Entity\ErrorCode::EMAIL_EXIST);
		}
		$len = strlen($password);
		if ($len < 6 || $len > 24) {
			$this->throwException('请输入6到24的密码！', \Entity\ErrorCode::PASSWORD_ERROR);
		}
		$password = \Util\User::encodePassword($password);
		$userId = \Data\User::instance()->addUser($email, $password, $ip);
        $user = array(
            'Username' => $username,
            'BreedId' => $breedId,
            'Sex' => $sex,
        );
        \Data\User::instance()->updateById($userId, $user);
        $this->setUserLoginMask($mask, $userId, $ip);
        \Data\User::instance()->addLoginLog($userId, time(), $ip);
        \Data\User::instance()->setUserLoginMask($mask, $userId);
		return $userId;
	}

	public function registerOrLoginBindOAuth($mask, $email, $password, $username, $ip) {
		if (!\Lib\Util\Comm::checkEmailFormat($email)) {
			$this->throwException('请输入正确的Email', \Entity\ErrorCode::EMAIL_FORMAT);
		}
		// 获取第三方用户信息
		$authInfo = $this->getOAuthInfoByMask($mask);
		if (!$authInfo) {
			$this->throwException('没有第三方登陆信息', \Entity\ErrorCode::NO_OAUTH_INFO);
		}
		// 判断第三方用户是否绑定账号
		$userId = $this->getUserIdByAuthId($authInfo['OAuthId'], $ip);
		if ($userId) {
			\Business\User::instance()->setUserLoginMask($mask, $userId, $ip);
			$this->throwException('已经登陆', \Entity\ErrorCode::IS_LOGIN);
		}
		// 判断输入的用户是否存在
		$user = $this->getUserInfoByEmail($email);
		if ($user) {
			// 登陆并且绑定账号
			$this->login($email, $password, $mask, $ip);
			\Data\OAuth::instance()->addOAuthUser($user['UserId'], $authInfo['OAuthId']);
			return;
		}
		// 注册并且绑定账号
		$len = strlen($password);
		if ($len < 6 || $len > 24) {
			$this->throwException('请输入6到24的密码！', \Entity\ErrorCode::PASSWORD_ERROR);
		}
		$len = strlen($username);
		if ($len < 2 || $len > 24) {
			$this->throwException('的昵称长度不符合规范！', \Entity\ErrorCode::USER_NAME_ERROR);
		}
		$userId = \Data\User::instance()->addUser($email, $password, $ip, $username, $authInfo['Photo']);
		\Data\OAuth::instance()->addOAuthUser($userId, $authInfo['OAuthId']);
		$this->setUserLoginMask($mask, $userId, $ip);
		\Data\User::instance()->addLoginLog($userId, time(), $ip);
		\Data\User::instance()->setUserLoginMask($mask, $userId);
	}

	public function saveUserInfo($userId, $username, $sex, $birthday, $experience, $city, $desc) {
		$len = strlen($username);
		if ($len < 4 || $len > 12) {
			$this->throwException('请输入4到12的狗狗名称！', \Entity\ErrorCode::USERNAME_EXIST);
		}
		if (!$city) {
			$this->throwException('请选择地区！');
		}
		if (!$birthday) {
			$this->throwException('请填写生日！');
		}

		$data = array(
			'Username' => $username,
			'Sex' => $sex,
			'Birthday' => $birthday,
			'Experience' => $experience,
			'City' => $city,
			'Desc' => $desc,
		);
		\Data\User::instance()->updateById($userId, $data);
	}

	public function login($email, $password, $userMask, $ip, $verify = null) {
		$email = strtolower($email);
        if ($verify != null) {
            $this->checkVerify($verify, $userMask);
        }
		$info = \Data\User::instance()->getUserInfoByEmail($email);
		if (!$info) {
			$info = \Data\User::instance()->getUserInfoByUsername($email);
		}
		// 判断用用户存在
		if (!$info) {
			$this->throwException('用户不存在！', \Entity\ErrorCode::EMAIL_EXIST);
		} else if ($info['Status'] != \Data\User::IS_YES) {
			$this->throwException('账号已被禁用，请与管理员联系！', \Entity\ErrorCode::EMAIL_EXIST);
		}
		// 判断密码
		if ($info['Password'] != \Util\User::encodePassword($password)) {
			$this->throwException('密码错误', \Entity\ErrorCode::PASSWORD_ERROR);
		}
		// 登录成功
		$userId = $info['UserId'];
		$this->setUserLoginMask($userMask, $userId, $ip);
		\Data\User::instance()->addLoginLog($userId, time(), $ip);
		\Data\User::instance()->setUserLoginMask($userMask, $userId);
	}

	public function setUserLoginMask($userMask, $userId, $ip) {
		\Data\User::instance()->addLoginLog($userId, time(), $ip);
		\Data\User::instance()->setUserLoginMask($userMask, $userId);
	}

	public function setUserAuthId($userMask, $authId) {
		\Data\User::instance()->setUserAuthId($userMask, $authId);
	}

	public function loginByOAuth($authId, $userMask) {
		\Data\User::instance()->setUserAuthId($userMask, $authId);
	}

	public function loginOut($userMask) {
		\Data\User::instance()->delUserLoginMask($userMask);
	}

	/**
	 * 获取当前的用户信息.
	 *
	 * @param string $mask 用户cookie唯一标识.
	 *
	 * @return array
	 */
	public function getCurrentUserInfo($mask) {
		// 通过mask获取用户id
		$info = \Data\User::instance()->getCurrentUserInfo($mask);
		// 通过uid获取用户信息
		return $info;
	}

	public function getOAuthInfoByMask($mask) {
		return \Data\User::instance()->getOAuthInfoByMask($mask);
	}

	public function getUserInfoByEmail($email, $isOk = false) {
		return \Data\User::instance()->getUserInfoByEmail($email, $isOk);
	}

	public function getUserInfoByUsername($username, $isOk = false) {
		return \Data\User::instance()->getUserInfoByUsername($username, $isOk);
	}

	/**
	 * 检查验证码是否正确.
	 *
	 * @param string $verify 用户输入的验证码.
	 * @param string $mask 用户cookie唯一标识.
	 * @param boolean $isReturn 是否用返回的方式返回验证结果.
	 * @return boolean
	 *
	 * @throws \Lib\Exception\Business
	 */
	public function checkVerify($verify, $mask, $isReturn = false) {
		$trueVerify = $this->getVerify($mask);
		try {
			if (!$trueVerify) {
				$this->throwException('验证码过期！', \Entity\ErrorCode::VERIFY_ERROR);
			}
			if (strtolower($trueVerify) != strtolower($verify)) {
				$this->throwException('验证码错误！', \Entity\ErrorCode::VERIFY_ERROR);
			}
			return true;
		} catch (\Lib\Exception\Business $e) {
			if ($isReturn) {
				return false;
			}
			throw $e;
		}
	}

	public function updateUserPhoto($userId, $file) {
		\Data\User::instance()->updateUserPhoto($userId, $file);
	}

	/**
	 * 得到用户的验证码.
	 *
	 * @param string $userMask 用户cookie唯一标识.
	 *
	 * @return string
	 */
	public function getVerify($userMask) {
		return \Data\Verify::instance()->getVerify($userMask);
	}

	/**
	 * 设置用户验证码.
	 *
	 * @param string $userMask 用户cookie唯一标识.
	 * @param string $val 验证码的值.
	 *
	 * @return void
	 */
	public function setVerify($userMask, $val) {
		\Data\Verify::instance()->setVerify($userMask, $val);
	}

	public function replaceQQ($openId, $nickname, $sex, $photo) {
		$data = array(
			'Type' => \Data\OAuth::TYPE_QQ,
			'OpenId' => $openId,
			'Nickname' => $nickname,
			'Sex' => $sex,
			'Photo' => $photo,
		);
		return \Data\OAuth::instance()->replaceInfo($data);
	}

    public function replaceWeibo($openId, $nickname, $sex, $photo) {
        $data = array(
            'Type' => \Data\OAuth::TYPE_WEIBO,
            'OpenId' => $openId,
            'Nickname' => $nickname,
            'Sex' => $sex,
            'Photo' => $photo,
        );
        return \Data\OAuth::instance()->replaceInfo($data);
    }

	public function updateUserInfo($userId, $user) {
		\Data\User::instance()->updateUserInfo($userId, $user);
	}

	public function getUserDetailInfo($userId) {
		$userInfo = \Data\User::instance()->getUserInfoByUid($userId);
		if (!$userInfo) {
			return array();
		}
		$userInfo['cityInfo'] = array();
		$userInfo['breed'] = '';
		if ($userInfo['City']) {
			$userInfo['cityInfo'] = \Business\City::instance()->getCityInfoByCode($userInfo['City']);
		}
		if ($userInfo['BreedId']) {
			$userInfo['breed'] = \Business\Breed::instance()->getNameById($userInfo['BreedId']);
		}
		return $userInfo;
	}

	public function saveCondition($userId, $city, $age, $sex, $weight, $length, $height, $color, $breed) {
		$breedNames = explode(',', $breed);
		foreach ($breedNames as $k => $v) {
			$breedNames[$k] = trim($v);
			if (!$v) {
				unset($breedNames[$k]);
			}
		}
		$breedIds = array();
		if ($breedNames) {
			$breedIds = \Data\Breed::instance()->getBreedIdsByNames($breedNames);
		}
		\Data\UserCondition::instance()->saveCondition($userId, $city, $age, $sex, $weight, $length, $height, $color, $breedIds);
	}

	public function saveUserMaster($userId, $nickname, $sex, $experience, $dogNumber, $profession, $birthday, $desc) {
		\Data\UserMaster::instance()->saveUserMaster($userId, $nickname, $sex, $experience, $dogNumber, $profession, $birthday, $desc);
	}

	public function getUserConditionByUserId($userId) {
		$userCondition = \Data\UserCondition::instance()->getUserConditionByUserId($userId);
		$cityCode = $userCondition['City'];

		$userCondition['breedNames'] = '';
		if (!$cityCode) {
			$userCondition['cityName'] = '不限';
		} else {
			$city = \Business\City::instance()->getCityInfoByCode($cityCode);
			$userCondition['cityName'] = implode('', $city);
		}

		if ($userCondition['Breeds']) {
			$breedIdArr = explode(',', $userCondition['Breeds']);
			$names = \Business\Breed::instance()->getNameByIds($breedIdArr);
			$userCondition['breedNames'] = implode(', ', $names);
		}
		return $userCondition;
	}

	public function getUserMasterInfoByUserId($userId) {
		return \Data\UserMaster::instance()->getUserMasterInfoByUserId($userId);
	}

	public function addPhoto($userId, $title, $desc, $path) {
		\Data\UserPhoto::instance()->addPhoto($userId, $title, $desc, $path);
	}

	public function delPhoto($userId, $photoId) {
		\Data\UserPhoto::instance()->delPhoto($userId, $photoId);
	}

	public function getUserPhotosByUserId($userId, $limit = null) {
		$result = \Data\UserPhoto::instance()->getUserPhotosByUserId($userId, $limit);
		return $result;
	}

	public function getPhotoDetailByPhotoId($photoId) {
		$result = \Data\UserPhoto::instance()->getDetailById($photoId);
		return $result;
	}

	public function updatePhoto($userId, $photoId, $title, $desc) {
		\Data\UserPhoto::instance()->updatePhoto($userId, $photoId, $title, $desc);
	}

	public function getUserIdByAuthId($authId, $ip, $initUser = false) {
		$userId = \Data\OAuth::instance()->getUserIdByAuthId($authId);
		if ($userId) {
			return $userId;
		}
		if (!$initUser) {
			return $userId;
		}
		// 初始化用户数据
		$authInfo = \Data\OAuth::instance()->getById($authId);
		$userInfo = array(
			'Email' => '',
			'Username' => $authInfo['Nickname'] . '的狗狗',
			'CreateTime' => time(),
			'UpdateTime' => time(),
			'RegisterIp' => $ip,
			'Photo' => $authInfo['Photo'],
		);
		$userId = \Data\User::instance()->insert($userInfo);
		\Data\OAuth::instance()->addOAuthUser($userId, $authId);
		return $userId;
	}

	public function getIndexUser() {
		$users = \Data\User::instance()->getIndexUser();
		foreach ($users as $k => $u) {
			if ($u['City']) {
				$users[$k]['cityInfo'] = \Business\City::instance()->getCityInfoByCode($u['City']);
			} else {
				$users[$k]['cityInfo'] = array();
			}
 		}
		return $users;
	}

	public function getBlindIndexDogs() {
		$breedIds = \Data\User::instance()->getMaxMoreBreedIds(4);
		if (!$breedIds) {
			return array();
		}
		$breedInfo = \Data\Breed::instance()->getByIds($breedIds);
		// 品种下的狗狗
		foreach ($breedInfo as & $breed) {
			$user = \Data\User::instance()->getTopUserByBreedId($breed['Id'], 10);
			foreach ($user as & $u) {
				$u['cityInfo'] = \Business\City::instance()->getCityInfoByCode($u['City']);
			}
			$breed['User'] = $user;
		}
		return $breedInfo;
	}

	public function getUserLikeDog($limit, $city = 0, $breed = 0, $sex = 0, $notUserId = 0) {
		$userIds = array();
		if ($notUserId) {
			$userIds[] = $notUserId;
		}
		$likeDogs = $this->search($limit, $city, $breed, $sex, true, $userIds);
		foreach ($likeDogs as $val) {
			$userIds[] = $val['UserId'];
		}
		$hasCount = count($userIds);
		$diff = $limit - $hasCount + 1;
		$dogs = array();
		if ($diff) {
			$dogs = $this->search($diff, 0, 0, 0, true, $userIds);
		}
		$dogs = array_merge($likeDogs, $dogs);
		return $dogs;
	}

	public function search($pager, $city = 0, $breed = 0, $sex = 0, $hasPhoto = false, $notUserIds = array()) {
		$breedIds = array();
		if ($breed) {
			$breed = str_replace('，', ',', $breed);
			$tmp = explode(',', $breed);
			foreach ($tmp as $k => $v) {
				$tmp[$k] = $v ? trim($v) : '';
			}
			$tmp = array_unique($tmp);
			$tmp = array_diff($tmp, array(false, '', 0, null));
			$breedIds = \Data\Breed::instance()->getBreedIdsByNames($tmp);
		}
		$dogs = \Data\User::instance()->search($pager, $city, $breedIds, $sex, $hasPhoto, $notUserIds);

		$bIds = array();
		foreach ($dogs as $k => $u) {
			$dogs[$k]['cityInfo'] = \Business\City::instance()->getCityInfoByCode($u['City']);
			$bIds[$u['BreedId']] = $u['BreedId'];
		}
		if ($bIds) {
			$breedInfo = \Data\Breed::instance()->getByIds($bIds);
			foreach ($dogs as $k => $u) {
				$dogs[$k]['breedName'] = '';
				if ($u['BreedId']) {
					$dogs[$k]['breedName'] = $breedInfo[$u['BreedId']]['Name'];
				}
			}
		}
		return $dogs;
	}

	public function follow($userId, $followUserId) {
        if ($userId == $followUserId) {
            $this->throwException('不能关注自己');
        }
		$userId = \Data\User::instance()->getUserIdByUserId($userId);
		if (!$userId) {
			$this->throwException('关注用户不存在');
		}
		return \Data\UserFollow::instance()->follow($userId, $followUserId);
	}

	public function followDel($userId, $followUserId) {
		return \Data\UserFollow::instance()->followDel($userId, $followUserId);
	}

    public function getUserFollowNumber($userId) {
        $number = \Data\UserFollow::instance()->getUserFollowNumber($userId);
        return $number;
    }

	public function getUserFansNumber($userId) {
		$number = \Data\UserFollow::instance()->getUserFansNumber($userId);
		return $number;
	}

    public function getFollowUsers($userId, $pager) {
        $users = \Data\UserFollow::instance()->getFollowUsers($userId, $pager);
        $bIds = array();
        foreach ($users as $k => $u) {
            $users[$k]['cityInfo'] = \Business\City::instance()->getCityInfoByCode($u['City']);
            $bIds[$u['BreedId']] = $u['BreedId'];
        }
        $breedInfo = $bIds ?  \Data\Breed::instance()->getByIds($bIds) : array();
        foreach ($users as $k => $u) {
            $users[$k]['breedName'] = '';
            if ($u['BreedId']) {
                $users[$k]['breedName'] = $breedInfo[$u['BreedId']]['Name'];
            }
        }
        return $users;
    }

    public function getFansUsers($userId, $pager) {
        $users = \Data\UserFollow::instance()->getFansUsers($userId, $pager);
        $bIds = array();
        foreach ($users as $k => $u) {
            $users[$k]['cityInfo'] = \Business\City::instance()->getCityInfoByCode($u['City']);
            $bIds[$u['BreedId']] = $u['BreedId'];
        }
        $breedInfo = $bIds ?  \Data\Breed::instance()->getByIds($bIds) : array();
        foreach ($users as $k => $u) {
            $users[$k]['breedName'] = '';
            if ($u['BreedId']) {
                $users[$k]['breedName'] = $breedInfo[$u['BreedId']]['Name'];
            }
        }
        return $users;
    }

	public function isFollow($userId, $followUserId) {
		$data = \Data\UserFollow::instance()->getByUserIdAndFollowUserId($userId, $followUserId);
		return $data ? true : false;
	}

    public function addHello($userId, $toUserId, $content) {
        if (!$userId || !$toUserId) {
            $this->throwException('参数错误');
        }
        if (!$content) {
            $this->throwException('请填写内容');
        }
        if ($userId == $toUserId) {
            $this->throwException('不能问候自己');
        }
        if (strlen($content) > 300) {
            $this->throwException('内容过长');
        }
        \Data\Hello::instance()->addHello($userId, $toUserId, $content);
    }

    public function delFollowUser($userId, $followUserId) {
        \Data\UserFollow::instance()->delFollowUser($userId, $followUserId);
    }

    public function getUserNotReadHelloCount($userId) {
        $count = \Data\Hello::instance()->getUserNotReadHelloCount($userId);
        return $count;
    }

    public function getUserHello($userId, $pager) {
        $message = \Data\Hello::instance()->getUserHello($userId, $pager);
        $userIds = array();
        foreach ($message as $val) {
            $userIds[$val['UserId']] = $val['UserId'];
            $userIds[$val['ToUserId']] = $val['ToUserId'];
        }
        $users = $userIds ? \Data\User::instance()->getUserByIds($userIds) : array();
        foreach ($users as $key => $val) {
            $users[$key]['cityInfo'] = \Business\City::instance()->getCityInfoByCode($val['City']);
        }
        foreach ($message as $key => $val) {
            $i = $val['ToUserId'];
            if ($val['ToUserId'] == $userId) {
                $i = $val['UserId'];
            }
            $message[$key]['UserInfo'] = !empty($users[$i]) ? $users[$i] : array();
        }
        return $message;
    }

    public function getHelloDetail($helloId, $userId) {
        $hello = \Data\Hello::instance()->getHelloByIdAndUserId($helloId, $userId);
        $uid = $userId != $hello['UserId'] ? $hello['UserId'] : $hello['ToUserId'];
        if ($hello) {
            $hello['UserInfo'] = \Business\User::instance()->getUserDetailInfo($uid);
        }
        \Data\Hello::instance()->setHelloViewEd($helloId, $userId);
        return $hello;
    }

	public function addHelloReply($helloId, $userId, $content) {
        $hello = \Data\Hello::instance()->getHelloByIdAndUserId($helloId, $userId);
        if (!$hello) {
            $this->throwException('数据不存在');
        }
		\Data\HelloReply::instance()->addHelloReply($helloId, $userId, $content);
        if ($hello['UserId'] == $userId) {
            \Data\Hello::instance()->updateReadStatus($helloId, 'IsRead', \Data\Base::IS_NO);
        } else {
            \Data\Hello::instance()->updateReadStatus($helloId, 'SendIsRead', \Data\Base::IS_NO);
        }
	}

    public function getHelloReply($helloId) {
        $result = \Data\HelloReply::instance()->getHelloReply($helloId);
        return $result;
    }

}